import router from '@/routers';
import { loginRoutePath, STORAGE_TOKEN_KEY } from '@/types/meta';
import { notification } from 'ant-design-vue';
import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios';

export const REQUEST_TOKEN_KEY = 'Access-Token';

// 创建 axios 实例
const request = axios.create({
	baseURL: import.meta.env.VITE_API_BASE_URL,
	timeout: 6000,
});

// 异常拦截处理器
const errorHandler = (error: AxiosError): Promise<any> => {
	if (error.response) {
		const { status } = error.response;
		// 401 未登录/未授权
		if (status === 401) {
			notification.error({
				message: 'Unauthorized',
				description: 'Authorization verification failed',
			});
			localStorage.removeItem(STORAGE_TOKEN_KEY);
			setTimeout(() => {
				router.push({
					path: loginRoutePath,
					replace: true,
				});
			}, 2000);
		}
	}
	return Promise.reject(error);
};

// 请求拦截器
const requestHandler = (config: InternalAxiosRequestConfig<any>): InternalAxiosRequestConfig => {
	const savedToken = localStorage.getItem(STORAGE_TOKEN_KEY);
	if (savedToken) {
		config.headers!.Authorization = `Bearer ${savedToken}`;
	}
	return config;
};

// Add a request interceptor
request.interceptors.request.use(requestHandler, errorHandler);

// 响应拦截器
const responseHandler = (response: AxiosResponse): AxiosResponse<any> | Promise<any> | any => {
	return response.data;
};

// Add a response interceptor
request.interceptors.response.use(responseHandler, errorHandler);

export default request;
